package yur.wedding.common.utils;

import com.alibaba.fastjson.JSONObject;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.*;
import java.nio.charset.Charset;

import com.itextpdf.text.Document;
import com.itextpdf.tool.xml.XMLWorkerFontProvider;
import com.itextpdf.tool.xml.XMLWorkerHelper;

public class PdfUtilsTest {




    /**
     * 通过html生成文件
     * @param htmlContent  html格式内容
     * @param file  输出文件file
     */
    public String  createdPdfByItextHtml(String htmlContent,String file){
        InputStream inputStream = null;
        FileOutputStream outputStream = null;
        String url="D:/imgcs/" +file+".pdf";
        PdfWriter writer = null;
        try {
            // 1. 获取生成pdf的html内容
            inputStream= new ByteArrayInputStream(htmlContent.getBytes("utf-8"));
            outputStream = new FileOutputStream(url);
            Document document = new Document();
            writer = PdfWriter.getInstance(document, outputStream);
            document.open();
            // 2. 添加字体
            XMLWorkerFontProvider fontImp = new XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS);
            fontImp.register("/statics/fonts/fontawesome-webfont.ttf");
            // 3. 设置编码
            XMLWorkerHelper.getInstance().parseXHtml(writer, document, inputStream, Charset.forName("UTF-8"),fontImp);
            // 4. 关闭,(不关闭则会生成无效pdf)
            document.close();

            //5.把浏览器上传的文件复制到希望的位置

        } catch (Exception ex) {
            ex.printStackTrace();
        }finally {
            try {
                if(writer!=null){
                    writer.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
            }catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return "wedding_admin/static/"+file+".pdf";
    }












}

